package com.iotest.path;

import org.junit.Test;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Stream;

/**
 * @Author: huhx
 * @Date: 2017-11-10 下午 4:52
 */
public class FilesTest {

    @Test
    public void writeFile_1() throws IOException {
        Path path = Paths.get("file/huhx.txt");
        byte[] fileArray = Files.readAllBytes(path);
        List<String> strings = Files.readAllLines(path);

        Path path2 = Paths.get("file/huhx2.txt");
        Files.write(path2, fileArray);
    }

    @Test
    public void bufferedRead_1() throws IOException {
        Charset charset = Charset.forName("UTF-8");
        Path path = Paths.get("file/huhx.txt");
        try (BufferedReader reader = Files.newBufferedReader(path, charset)) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException x) {
            System.err.format("IOException: %s%n", x);
        }
    }

    @Test
    public void bufferedWrite_1() throws IOException {
        Charset charset = Charset.forName("UTF-8");
        Path path = Paths.get("file/huhx3.txt");
        String string = "I love you.\nhello world";
        try (BufferedWriter writer = Files.newBufferedWriter(path, charset)) {
            writer.write(string, 0, string.length());
        } catch (IOException x) {
            System.err.format("IOException: %s%n", x);
        }
    }

    @Test
    public void createFile_1() throws IOException {
        Files.createFile(Paths.get("file/huhx4.txt"));
        Path tempFile = Files.createTempFile(null, ".myapp");
        System.out.println(tempFile.toAbsolutePath().toString());
    }

    @Test
    public void listFileNames() throws IOException {
        Path path = Paths.get("file");
        Stream<Path> pathStream = Files.list(path);
//        Iterator<Path> iterator = pathStream.iterator();

        System.out.println(pathStream.count());
    }

}
